package ebj.common.httpclient;

import java.net.URI;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.DefaultRedirectHandler;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

import ebj.common.logging.CommonLogger;


public class RedirectAnalysisTest {
	private static CommonLogger logger = new CommonLogger(RedirectAnalysisTest.class);
	private static int counter = 0;
	private static String last_time_target_url = "";
	
//	static String target_url = "http://media.mobilecore.com/get?t=s&aff_id=69&id=101282&fos=Android&p1=aff_sub&v1=native_Uvy_UB-bgv965RDdrRf3PjNk-zUd-Rmd-zD1-zm40Ai9mWyW5R00mgK85RmL-fKzpAq15R63-8KdsA96ULik5cywsj-BswP8PBPdmBmLrj79sBi_P&p2=aff_sub2&v2=AF8PBFEsAP8sRf8PjD8-jy_mwF0ug0q-RxoPzPoPwF3nwU40Aqz5RD0mcfqPRxkPjD0TA7ksvy15fKdUvyk5Rx3rjx3rjx30ZKkuc-95R0oPRm8Pj080A-bm&p3=aff_sub3&v3=g2WsR1k0Z-GpLiXTZ98sR1E0ZKCszdwpv1opA7lIg-LugK90Zikmc-C5RF80Ai_TANqPw0E-R0dPwf8-RDdPjf0mvqdpWikIR1EPwU0mv-VsANqmv_o0Ay3U&p4=aff_sub4&v4=7qhsZPqPz08PfK9mLKJ5R0oPj0EPR0vPjUz-0KzscEGsgFqP0K6ugshsANqPa3LPj08Pj00UBihTB96sR18nwU8Pj08P0KosL0qPfK_mLfqPxKwUBPqrjU1Px0&aff_sub1=987";
	static String target_url = "http://media.mobilecore.com/get?t=s&aff_id=69&id=101282&fos=Android&p1=aff_sub&v1=native_Uvy_UB-bgv965RDvrRP1Pjx3PR6dPjN1-z6zPRx40Ai9mWyW5R00mgK85RmL-fKzpAq15R63-8KdsA96ULik5cywsj-BswP8PBPdmBmLrj79sBi_PA&p2=aff_sub2&v2=F8PBFEsAP8sRf8PjD8-jy_mwF0ug0qPwDEnwD1-a3kPj0oPwP10Aqz5RD0mcfqPRxkPjD0TA7ksvy15fKdUvyk5Rx3rjx3rjx30ZKkuc-95R0oPRm8Pj080A-&p3=aff_sub3&v3=bmg2WsR1k0Z-GpLiXTZ98sR1E0ZKCszdwpv1opA7lIg-LugK90Zikmc-C5RF80Ai_TANqPw0E-R0dPwU8rjfzPjm0mvqdpWikIR1EPwU0mv-VsANqmv_o0Ay3&p4=aff_sub4&v4=U7qhsZPqPz08PfK9mLKJ5R0oPj0EPRxL-jPvrfKzscEGsgFqP0K6ugshsANqPa3LPj08Pj00UBihTB96sR18nwU8Pj08P0KosL0qPfK_mLfqPxKwUBPqPR0vrjm0&aff_sub1=987";
	
	static String result_window_location_url = "http://trkyad.com/?a=2997&c=1243&s1=&s2=8132579206&s3=AP&s4=3101";
	
	static String last_url = "http://qianxianyuan.com/click.php?c=360&key=8g9404d5k05avwpk2y4ue4hm&Click_ID=APPIA143245076032282982298886144&packageName=com.lazyswipe&aaid=&idfa=&subpub_id=3101";
	
	@SuppressWarnings("deprecation")
	public static void main(String[] args) {
		DefaultHttpClient httpClient = new DefaultHttpClient();
		
		try {
			httpClient.setRedirectHandler(new DefaultRedirectHandler(){
				@Override
				public boolean isRedirectRequested(HttpResponse response,
						HttpContext context) {
					boolean isRedirectReq = super.isRedirectRequested(response, context);
					logger.info(">>>||||||||||||||||||<<<");
					logger.info("isRedirectReq=" + isRedirectReq);
					if (isRedirectReq) {
						logger.info("The " + (++counter) + " time.");
						int response_code = response.getStatusLine().getStatusCode();
						Header[] headers2 = response.getAllHeaders();
						for (Header header : headers2) {
							logger.info(header.getName() + " : " + header.getValue());
						}
						
						if (HttpStatus.SC_MOVED_PERMANENTLY == response_code) {
							logger.info("Is " + HttpStatus.SC_MOVED_PERMANENTLY + " redirect.");
						}else if (HttpStatus.SC_MOVED_TEMPORARILY == response_code) {
							logger.info("Is " + HttpStatus.SC_MOVED_TEMPORARILY + " redirect.");
						}else {
							logger.info("response_code = " + response_code);
						}
						Header[] headers = response.getHeaders("Location");
						if (headers.length > 0) {
							String redirect_location_url = headers[0].getValue();
							last_time_target_url = redirect_location_url;
							boolean isGoolglePlayUrl = MyTools.isGooglePlayUrl(redirect_location_url);
							logger.info("isGoolglePlayUrl=" + isGoolglePlayUrl + ", redirect_location_url >>> " + redirect_location_url);
						}
					}else {
						logger.info("The last time redirect target url >>> " + last_time_target_url);
					}
					
					return isRedirectReq;
				}
			});
			HttpGet httpGet = new HttpGet(target_url);
			HttpResponse response = httpClient.execute(httpGet);
			int rsp_code = response.getStatusLine().getStatusCode();
			logger.info("rsp_code = " + rsp_code);
			// httpGet.abort();
			logger.info("httpGet aborted.");
			String result = EntityUtils.toString(response.getEntity());
			logger.info("result=" + result);
		} catch (Exception e) {
			// e.printStackTrace();
			logger.error("Error", e);
		} finally{
			httpClient.close();
		}
	}
}

class MyTools{
	private static final String PLAY_GOOGLE_COM = "play.google.com";
    private static final String MARKET_ANDROID_COM = "market.android.com";
    private static final String MARKET = "market";
	
	public static boolean isGooglePlayUrl(final String url) {
        if (url == null) {
            return false;
        }

        final URI uri = URI.create(url);
        final String scheme = uri.getScheme();
        final String host = uri.getHost();

        if (PLAY_GOOGLE_COM.equals(host) || MARKET_ANDROID_COM.equals(host)) {
            return true;
        }

        if (MARKET.equals(scheme)) {
            return true;
        }

        return false;
    }
}
